package com.hankol.community.fragment

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.baselibrary.MessageBus
import com.baselibrary.bean.ClientStreamTimeline
import com.baselibrary.bean.StreamData
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.activity.BaseFragment
import com.hankol.community.R
import com.hankol.community.adapter.CommunityDiscoverHeadAdapter
import com.hankol.community.adapter.DiscoverChannelAdapter
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.DiscoverMultiBean
import com.hankol.community.databinding.FragmentMainDiscoverBinding
import com.hankol.community.viewmodel.CommunityViewModel
import kotlinx.android.synthetic.main.heard_top_square.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**发现
 * @time: 2022/3/24 10:05
 * @description:
 */
class CommunityDiscoverFragment : BaseFragment() {
    private lateinit var mBinding: FragmentMainDiscoverBinding
    private lateinit var mViewModel: CommunityViewModel
    private val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private val headView by lazy { LayoutInflater.from(activity).inflate(R.layout.layout_discover_head, null) }
    private val mAdapter: DiscoverChannelAdapter by lazy { DiscoverChannelAdapter(attachActivity,emptyList(), mViewModel, communityHelp) }
    private lateinit var selectedStreamData: StreamData.DataDTO.Data
    private lateinit var selectedClientStreamTimeline: ClientStreamTimeline
    private var selectedPosition = 0
    private var mCurrentPage = 1
    private var channelId = 0
    private var mCurrentCursor = "0"
    private var mIsLoadingMore = false
    private var mNoMoreData = false
    private lateinit var headRv: RecyclerView
    private var listData: ArrayList<DiscoverMultiBean> = ArrayList()

    companion object {

        fun newInstance(): CommunityDiscoverFragment {
            return CommunityDiscoverFragment()
        }
    }

    override fun init() {
        mBinding = getDataBinding<FragmentMainDiscoverBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(CommunityViewModel::class.java)
        mViewModel = getFragmentViewModelProvider(this).get(CommunityViewModel::class.java)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        refreshData()
        initView()
        addObserver()
        initListener()

    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_main_discover
    }

    private fun initListener() {
    }


    private fun initView() {
        mBinding.llLoading.visibility = View.VISIBLE
        headRv = headView.findViewById(R.id.rv_discover_head)
        MarginUtils.setViewGroupMarginTopIncludeStatusBar(attachActivity, mBinding.srlDiscover,44)
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        mBinding.rvDiscover.addItemDecoration(StaggeredItemDecoration(context, 5F, true))
        mBinding.rvDiscover.itemAnimator = null
        mBinding.rvDiscover.layoutManager = layoutManager
        mBinding.rvDiscover.isNestedScrollingEnabled = true
        mAdapter.setType(channelId)
        mBinding.rvDiscover.adapter = mAdapter
        mAdapter.addHeaderView(headView)
        mAdapter.setCallback(object : DiscoverChannelAdapter.Callback {
            override fun onClickLike(position: Int, item: StreamData.DataDTO.Data) {
                selectedStreamData = item
                selectedPosition = position
                val tlObj = item.data
                val tlStr = GsonUtils.toJson(tlObj)
                selectedClientStreamTimeline = GsonUtils.parseJsonToBean(tlStr, ClientStreamTimeline::class.java)
                mViewModel.reqSupport(!selectedClientStreamTimeline.isSupported, 4, selectedClientStreamTimeline.id)
                SensorsDataManager.instance.giveLike(selectedClientStreamTimeline.isSupported, "首页-发现页", "动态外部", SpanUtils.appendCut(selectedClientStreamTimeline.content))
            }
        })
        mBinding.rvDiscover.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val positions = layoutManager.findLastVisibleItemPositions(null)
                //提前10个开始预加载
                if (dy > 0 && !mIsLoadingMore && positions[0] >= mAdapter.data.size - 10) {
                    mIsLoadingMore = true
                    mCurrentPage++
                    loadStream()
                }
            }
        })
        mBinding.srlDiscover.setOnRefreshListener { _ -> refreshData() }
        mBinding.srlDiscover.setOnLoadMoreListener { _ ->
            if (mIsLoadingMore) {
                return@setOnLoadMoreListener
            }
            mCurrentPage++
            loadStream()
        }

    }

    private fun addObserver() {
        //推荐页和视频页瀑布流
        mViewModel.homeStreamLD.observe(viewLifecycleOwner, Observer {
            mBinding.srlDiscover.finishRefresh()
            if (it?.getData() != null) {
                mCurrentCursor = it.nextCursor
                if (mCurrentPage == 1) {
                    mAdapter.setNewData(it.getData())
                } else {
                    mBinding.srlDiscover.finishLoadMore(1)
                    mIsLoadingMore = false
                    if (mAdapter != null) {
                        try {
                            mAdapter.addData(it.getData())
                        } catch (e: Exception) {
                        }
                    }
                }
                if (!it.hasnext) {
                    mNoMoreData = true
                    mBinding.srlDiscover.finishLoadMoreWithNoMoreData()
                }
            } else {
                mNoMoreData = true
                mBinding.srlDiscover.finishLoadMoreWithNoMoreData()
            }
        })

        //点赞
        mViewModel.supportLiveData.observe(viewLifecycleOwner, Observer { it ->
            if (it) {
                selectedClientStreamTimeline.supportNum = if (selectedClientStreamTimeline.isSupported) selectedClientStreamTimeline.supportNum.minus(1) else selectedClientStreamTimeline.supportNum.plus(1)
                selectedClientStreamTimeline.isSupported = !selectedClientStreamTimeline.isSupported
                selectedStreamData.data = selectedClientStreamTimeline
                mAdapter.notifyItemChanged(selectedPosition)
            }
        })

        mViewModel.homePageLd.observe(viewLifecycleOwner, Observer { it ->
            mBinding.llLoading.postDelayed(Runnable {
                mBinding.llLoading.visibility = View.GONE
            }, 100)
            if (it != null) {
                listData.clear()
                if (it.bannerVo.bannerConfigs.isNotEmpty()) {
                    listData.add(DiscoverMultiBean(DiscoverMultiBean.TYPE_BANNER, it.bannerVo))
                }
                if (it.plateVo.majorPlateConfig.isNotEmpty()) {
                    listData.add(DiscoverMultiBean(DiscoverMultiBean.TYPE_IMPORTANT, it.plateVo))
                }
                if (it.quickLink.isNotEmpty()) {
                    listData.add(DiscoverMultiBean(DiscoverMultiBean.TYPE_LOCK, it.quickLink))
                }
                if (it.plateVo.activityPlateConfig.isNotEmpty()) {
                    listData.add(DiscoverMultiBean(DiscoverMultiBean.TYPE_EXERCISE, it.plateVo))
                }
                headRv.adapter = CommunityDiscoverHeadAdapter(listData, requireActivity())
            }
        })
    }

    fun doRefresh() {
        mBinding.rvDiscover.scrollToPosition(0)
        mBinding.srlDiscover.autoRefresh()
    }

    private fun refreshData() {
        mCurrentPage = 1
        mCurrentCursor = "0"
        mNoMoreData = false
        mIsLoadingMore = false
        loadStream()
        loadHeaderData()
    }

    private fun loadHeaderData() {
        mViewModel.requestHomepageData()
    }

    private fun loadStream() {
        if (!mNoMoreData) {
            mViewModel.requestStream(channelId, mCurrentPage.toString(), mCurrentCursor)
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
    }

    @SuppressLint("SuspiciousIndentation")
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        val isPause = !isVisibleToUser
        if (attachActivity.checkNotNull()) {
            StatusBarUtil.setStatusBarDarkTheme(attachActivity, !isPause)
        }
    }

    override fun onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroyView()
    }

}